package com.ch.ms.server.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ch.ms.server.packet.MaplePacket;
import com.ch.ms.server.packet.MaplePacketHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;


/**
 * 对客户端发过来的报文进行解码,解码后生成 {@link MaplePacket}并交给 {@link com.ch.ms.server.base.client.MapleClientSession}来处理
 */
public class MaplePacketDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Map<MaplePacketHeader, Class<? extends MaplePacket>> supportedPacketClasses;


    public MaplePacketDecoder(Map<MaplePacketHeader, Class<? extends MaplePacket>> supportedPacketClasses) {
        this.supportedPacketClasses = supportedPacketClasses;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        String packetStr = in.toString(CharsetUtil.UTF_8);

        JSONObject packetJsonObject = JSON.parseObject(packetStr);

        MaplePacketHeader header = readHeader(packetJsonObject);
        if (!CollectionUtils.isEmpty(supportedPacketClasses) && supportedPacketClasses.containsKey(header))

            out.add(getMaplePacket(packetJsonObject, supportedPacketClasses.get(header)));
    }


    private MaplePacket getMaplePacket(JSONObject packetJsonObject, Class<? extends MaplePacket> clazz) {
        return JSONObject.parseObject(packetJsonObject.toJSONString(), clazz);
    }


    private MaplePacketHeader readHeader(JSONObject packetJsonObject) {


        return MaplePacketHeader.valueOf(packetJsonObject.getString("header"));
    }


}
